#!/usr/bin/python3
import cv2
import pickle
import sys
import Camera

cam_idx_list = [-1] * 4

def test_camera():
    with open("../configs/cam_idx.bin", 'rb') as cam_idx_file:
        cam_idx_list = pickle.load(cam_idx_file)
    
    cp = Camera.get_capture()

    for i in cam_idx_list:
        print(i)
        cp.open(i)
        if not cp.isOpened():
            continue
        while 1:
            _, frame = cp.read()
            if not _:
                continue
            cv2.imshow("cam" + str(frame.shape), frame)
            key = cv2.waitKey(1)
            if key == ord('q'):
                exit(0)
            elif key == ord('c'):
                break

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        test_camera()
        exit()
    
    print("How many web cam do your computer have?(include build-in cam)", end='')
    cam_num = int(input())
    if cam_num <= 1:
        print("No enough cam!")
        exit()

    cp = Camera.get_capture()
    
    for i in range(cam_num*2):
        print(i)
        cp.open(i)
        if not cp.isOpened():
            continue
        while 1:
            _, frame = cp.read()
            if not _:
                continue

            cv2.putText(frame, "Is the up/down/front/back cam ?(u/d/f/b)", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
            cv2.imshow("cam frame", frame)
            key = cv2.waitKey(1)
            if key == ord('u'):
                cam_idx_list[0] = i
                break
            elif key == ord('d'):
                cam_idx_list[1] = i
                break
            elif key == ord('f'):
                cam_idx_list[2] = i
                break
            elif key == ord('b'):
                cam_idx_list[3] = i
                break
            elif key == ord('q'):
                break
    cam_idx_file = open("../configs/cam_idx.bin", 'wb')
    print(cam_idx_list)
    pickle.dump(cam_idx_list, cam_idx_file)
    cam_idx_file.close()
